package com.wonghiu.framework.transport.netty.server;

import com.wonghiu.framework.cluster.directory.ProviderDirectory;
import com.wonghiu.framework.cluster.directory.imp.ZkProviderDirectory;
import com.wonghiu.framework.common.exception.HRpcException;
import com.wonghiu.framework.common.factory.SingletonFactory;
import com.wonghiu.framework.exchange.HRpcRequest;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Author wonghiu
 * @Date 2021/8/10 21:37
 * @Version 1.0.1
 */
@Slf4j
public class RpcRequestHandler {
    private final ProviderDirectory serviceProvider;

    public RpcRequestHandler() {
        serviceProvider = SingletonFactory.getInstance(ZkProviderDirectory.class);
    }

    /**
     * Processing rpcRequest: call the corresponding method, and then return the method
     */
    public Object handle(HRpcRequest rpcRequest) {
        Object service = serviceProvider.getService(rpcRequest.getRpcServiceName());
        return invokeTargetMethod(rpcRequest, service);
    }

    /**
     * get method execution results
     *
     * @param rpcRequest client request
     * @param service    service object
     * @return the result of the target method execution
     */
    private Object invokeTargetMethod(HRpcRequest rpcRequest, Object service) {
        Object result;
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            result = method.invoke(service, rpcRequest.getParameters());
            log.info("service:[{}] successful invoke method:[{}]", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
        } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException e) {
            throw new HRpcException(e.getMessage(), e);
        }
        return result;
    }
}
